import subprocess
import time
import csv
import sys
import os

title = ['编号', '进程号', '状态', '进程描述', '创建时间', '路径']
data = []

def Init():
    '''初始化'''
    '''
    try:
        with open('data.csv', 'r') as csvfile:
            reader = csv.reader(csvfile)
            for row in reader:
                data.append(row)
    except Exception as e:
        data.append(title)
    '''
    if not os.path.exists('data.csv'):
        data.append(title)
    else:
        with open('data.csv', 'r') as csvfile:
            reader = csv.reader(csvfile)
            for row in reader:
                if len(row) != 0:
                    data.append(row)

def Display():
    '''显示所有项目'''
    for row in data:
        print(row)

def Run():
    '''运行新项目'''
    #file_path = input('请输入文件路径：')
    #describe = input('请输入项目描述：')
    file_path = 'D:\js_website-0.0.1-SNAPSHOT.jar'
    describe = '聚数咨询后台'
    create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    if not os.path.exists(file_path):
        print('未能找到正确的文件，请确认文件路径后重试！')
        return
    cmd = 'javaw -jar ' + file_path
    sub = subprocess.Popen(cmd)
    if sub.poll() == None:
        re =  '启动成功'
        if len(data) == 1:
            index = 0
        else:
            index = data[len(data) - 1][0]
        data.append([str(int(index) + 1), str(sub.pid), '运行', describe, create_time, file_path])
    else:
        re =  '启动失败'
    print(re + '，进程号为：' + str(sub.pid))
    
def Restart():
    '''重启已有项目'''
    pro_id = input('请输入需要重启的项目编号：')
    #终止部分
    pid = GetPidById(pro_id)
    if pid == None:
        print('结束时未能找到正确的进程，请确认后重试！')
        return
    cmd_kill = "taskkill /f /t /im " + pid
    sign_kill = os.system(cmd_kill)
    #启动部分
    pro_path = GetPathById(pro_id)
    if pro_path == None:
        print('启动时未能找到正确的文件，请确认后重试！')
        return
    cmd_run = 'javaw -jar ' + pro_path
    sub = subprocess.Popen(cmd_run)
    sign_run = sub.poll()
    #修改状态
    SetStatusById(sign_run, pro_id, '运行', str(sub.pid))
    sign_kill >>= 8
    print('重启成功' if sign_kill == 0 and sign_run == None else '重启失败')
    
def Kill():
    '''结束已有项目'''
    pro_id = input('请输入需要终止的项目编号：')
    pid = GetPidById(pro_id)
    if pid == None:
        print('未能找到正确的进程，请确认后重试！')
        return
    cmd = "taskkill /f /t /im " + pid
    sign = os.system(cmd)
    sign >>= 8
    SetStatusById(sign, pro_id, '未运行')
    print('终止成功' if sign == 0 else '终止失败')

def Default():
    print('请输入正确的功能序号！')

def GetPathById(pro_id):
    '''根据编号获取文件路径'''
    for pro in data:
        if pro_id == pro[0]:
            return pro[len(pro) - 1]
    return None

def GetPidById(pro_id):
    '''根据编号获取进程号'''
    for pro in data:
        if pro_id == pro[0]:
            return pro[1]
    return None

def SetStatusById(sign, pro_id, status, pid = 'null'):
    '''根据编号设置状态'''
    if sign == 0 or sign == None:
        for pro in data:
            if pro_id == pro[0]:
                pro[2] = status
                pro[1] = pid

def EndWrite():
    '''把最新情况保存到csv文件中'''
    with open('data.csv', 'w') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerows(data)

def Exit():
    '''保存并退出'''
    EndWrite()
    sys.exit()

def Main():
    print('1.显示所有项目\n' +
          '2.运行新项目\n' +
          '3.重启已有项目\n' +
          '4.终止已有项目\n' +
          '0.退出')
    while(True):
        sign = input('请输入所选功能：')
        switch = {'1' : Display, '2' : Run, '3' : Restart, '4' : Kill, '0' : Exit}
        switch.get(sign, Default)()

if __name__ == '__main__':
    Init()
    Main()
    '''
    try:
        Init()
        Main()
    except:
        print ("未能正常退出！")
    EndWrite()
'''
